package org.example.designpatterns.singleton.demo3;

import lombok.SneakyThrows;

import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.util.Objects;

/**
 * @author Gong.Yang
 */
public class Demo {
    public static void main(String[] args) {
        String filePath = "object.txt";

        Singleton instance1 = Singleton.getInstance();
        writeObjectToFile(instance1, filePath);

        Singleton singleton1 = (Singleton) readObjectByFile(filePath);
        Singleton singleton2 = (Singleton) readObjectByFile(filePath);
        System.out.println(singleton1 == singleton2);
    }

    @SneakyThrows
    private static <T extends Serializable> void writeObjectToFile(T obj, String path) {
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(path));
        objectOutputStream.writeObject(obj);
        objectOutputStream.close();
    }

    @SneakyThrows
    private static Object readObjectByFile(String path) {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(path));
        Object o = objectInputStream.readObject();
        if (Objects.isNull(o)) {
            throw new RuntimeException();
        }
        objectInputStream.close();

        return o;
    }
}
